package api

import (
	"encoding/json"
	"net/http"
	"strconv"

	"github.com/ammyhaber/seckill/pkg/errcode"
	"github.com/ammyhaber/seckill/pkg/utils"
	"github.com/ammyhaber/seckill/service/inventory/model"
	"github.com/ammyhaber/seckill/service/inventory/service"
)

type InventoryAPI struct {
	inventoryService     *service.InventoryService
	inventoryLockService *service.InventoryLockService
}

func NewInventoryAPI(inventoryService *service.InventoryService) *InventoryAPI {
	return &InventoryAPI{inventoryService: inventoryService}
}

// SetInventoryLockService 设置库存锁定服务
func (a *InventoryAPI) SetInventoryLockService(inventoryLockService *service.InventoryLockService) {
	a.inventoryLockService = inventoryLockService
}

// LockInventory 锁定库存API
func (a *InventoryAPI) LockInventory(w http.ResponseWriter, r *http.Request) {
	// 解析请求参数
	var req model.InventoryLockRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		utils.Fail(w, errcode.InvalidParams, "请求参数解析失败")
		return
	}

	// 参数校验
	if req.OrderID == "" || req.ProductID <= 0 || req.Count <= 0 {
		utils.Fail(w, errcode.InvalidParams, "参数错误")
		return
	}

	// 锁定库存
	success, err := a.inventoryLockService.LockInventory(r.Context(), &req)
	if err != nil {
		utils.Fail(w, errcode.ServerError, err.Error())
		return
	}

	if !success {
		utils.Fail(w, errcode.InventoryNotEnough, errcode.GetMsg(errcode.InventoryNotEnough))
		return
	}

	utils.Success(w, map[string]bool{"success": true})
}

// ConfirmInventoryLock 确认库存锁定API
func (a *InventoryAPI) ConfirmInventoryLock(w http.ResponseWriter, r *http.Request) {
	// 解析请求参数
	var req model.InventoryLockConfirmRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		utils.Fail(w, errcode.InvalidParams, "请求参数解析失败")
		return
	}

	// 参数校验
	if req.OrderID == "" || req.ProductID <= 0 {
		utils.Fail(w, errcode.InvalidParams, "参数错误")
		return
	}

	// 确认库存锁定
	err := a.inventoryLockService.ConfirmInventoryDeduction(r.Context(), &req)
	if err != nil {
		utils.Fail(w, errcode.ServerError, err.Error())
		return
	}

	utils.Success(w, map[string]bool{"success": true})
}

// CancelInventoryLock 取消库存锁定API
func (a *InventoryAPI) CancelInventoryLock(w http.ResponseWriter, r *http.Request) {
	// 解析请求参数
	var req model.InventoryLockCancelRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		utils.Fail(w, errcode.InvalidParams, "请求参数解析失败")
		return
	}

	// 参数校验
	if req.OrderID == "" || req.ProductID <= 0 {
		utils.Fail(w, errcode.InvalidParams, "参数错误")
		return
	}

	// 取消库存锁定
	err := a.inventoryLockService.CancelInventoryDeduction(r.Context(), &req)
	if err != nil {
		utils.Fail(w, errcode.ServerError, err.Error())
		return
	}

	utils.Success(w, map[string]bool{"success": true})
}

// GetInventory 获取库存信息
func (a *InventoryAPI) GetInventory(w http.ResponseWriter, r *http.Request) {
	// 获取商品ID
	productIDStr := r.URL.Query().Get("product_id")
	if productIDStr == "" {
		utils.Fail(w, errcode.InvalidParams, "商品ID不能为空")
		return
	}

	productID, err := strconv.ParseInt(productIDStr, 10, 64)
	if err != nil {
		utils.Fail(w, errcode.InvalidParams, "商品ID格式错误")
		return
	}

	// 获取库存详情
	detail, err := a.inventoryService.GetInventoryDetail(r.Context(), productID)
	if err != nil {
		utils.Fail(w, errcode.ServerError, err.Error())
		return
	}

	utils.Success(w, detail)
}

// DecrInventory 扣减库存
type DecrInventoryRequest struct {
	ProductID int64 `json:"product_id"`
	Count     int   `json:"count"`
}

func (a *InventoryAPI) DecrInventory(w http.ResponseWriter, r *http.Request) {
	// 解析请求参数
	var req DecrInventoryRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		utils.Fail(w, errcode.InvalidParams, "请求参数解析失败")
		return
	}

	// 参数校验
	if req.ProductID <= 0 || req.Count <= 0 {
		utils.Fail(w, errcode.InvalidParams, "参数错误")
		return
	}

	// 扣减库存
	success, err := a.inventoryService.DecrInventory(r.Context(), req.ProductID, req.Count)
	if err != nil {
		utils.Fail(w, errcode.ServerError, err.Error())
		return
	}

	if !success {
		utils.Fail(w, errcode.InventoryNotEnough, errcode.GetMsg(errcode.InventoryNotEnough))
		return
	}

	utils.Success(w, map[string]bool{"success": true})
}

// ConfirmDeduction 确认扣减（订单支付成功后调用）
type ConfirmDeductionRequest struct {
	ProductID int64 `json:"product_id"`
	Count     int   `json:"count"`
}

func (a *InventoryAPI) ConfirmDeduction(w http.ResponseWriter, r *http.Request) {
	// 解析请求参数
	var req ConfirmDeductionRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		utils.Fail(w, errcode.InvalidParams, "请求参数解析失败")
		return
	}

	// 参数校验
	if req.ProductID <= 0 || req.Count <= 0 {
		utils.Fail(w, errcode.InvalidParams, "参数错误")
		return
	}

	// 确认扣减
	err := a.inventoryService.ConfirmDeduction(r.Context(), req.ProductID, req.Count)
	if err != nil {
		utils.Fail(w, errcode.ServerError, err.Error())
		return
	}

	utils.Success(w, map[string]bool{"success": true})
}

// CancelDeduction 取消扣减（订单取消时调用）
type CancelDeductionRequest struct {
	ProductID int64 `json:"product_id"`
	Count     int   `json:"count"`
}

func (a *InventoryAPI) CancelDeduction(w http.ResponseWriter, r *http.Request) {
	// 解析请求参数
	var req CancelDeductionRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		utils.Fail(w, errcode.InvalidParams, "请求参数解析失败")
		return
	}

	// 参数校验
	if req.ProductID <= 0 || req.Count <= 0 {
		utils.Fail(w, errcode.InvalidParams, "参数错误")
		return
	}

	// 取消扣减
	err := a.inventoryService.CancelDeduction(r.Context(), req.ProductID, req.Count)
	if err != nil {
		utils.Fail(w, errcode.ServerError, err.Error())
		return
	}

	utils.Success(w, map[string]bool{"success": true})
}
